// 定义单位及其对应的字节数
const unitsMapper = {
    B: 1,
    KB: 1024,
    MB: 1024 * 1024,
    GB: 1024 * 1024 * 1024,
    TB: 1024 * 1024 * 1024 * 1024
};

function fileSizeToBytes(sizeStr) {
    if (typeof sizeStr === "number") {
        return parseInt(sizeStr, 10)
    }
    // 使用正则表达式匹配数字和单位
    const match = sizeStr.match(/^(\d+)(\D*)$/);

    if (!match) {
        throw new Error('Invalid file size format');
    }

    // 提取数字和单位
    const [_, numStr, unitStr] = match;
    const num = parseFloat(numStr);
    const unit = unitStr.toUpperCase().trim();

    // 检查单位是否有效
    if (!(unit in unitsMapper)) {
        throw new Error(`Unsupported unit: ${unit}`);
    }

    // 计算并返回字节数
    return num * unitsMapper[unit];
}

const units = ['B', 'KB', 'MB', 'GB', 'TB'];

function formatFileSize(bytes) {
    if (bytes === 0) return '0 B';
    if (typeof bytes === "string") {
        if (bytes.match(/^(\d+)(\D*)$/)) {
            return bytes;
        }
        bytes = parseInt(bytes, 10);

    }
    let unitIndex = -1;
    while (Math.abs(bytes) >= 1024) {
        bytes /= 1024;
        unitIndex++;
    }
    return `${bytes.toFixed(2)} ${units[unitIndex + 1]}`;
}

const startFileTools = {
    fileSizeToBytes,
    formatFileSize
}
export default startFileTools;